#!/usr/bin/python3
#******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
"""
This is openEuler source counter script
"""

import sys
import os
import argparse
import re
import codecs

import sourcecounter

def check_pr(user_list, repo_list, owner, state, outfile):
    fp = codecs.open(outfile, mode='w', encoding="utf_8_sig")
    if not fp:
        return False
    header = "{},{},{},{},{},{}".format(
        "repo", "pr", "state", "type", "title", "user")
    print(header)
    fp.write("{}\n".format(header))

    src_counter = sourcecounter.SourceCounter()
    all_repo_flag = False
    if not repo_list:
        all_repo_flag = True

    for user in user_list:
        if all_repo_flag:
            page = 1
            repo_list_tmp = src_counter.get_repos(owner, page=page)
        else:
            repo_list_tmp = repo_list
        
        while len(repo_list_tmp):
            for repo in repo_list_tmp:
                print("{}:{}".format(user, repo))
                pr_page = 1
                pr_list = src_counter.get_pr_list(repo, owner, state=state, page=pr_page)
                while len(pr_list):
                    for pr in pr_list:
                        if pr["user"] != user:
                            continue
                        pr_url = "https://gitee.com/{}/{}/pulls/{}".format(owner, repo, pr["number"])
                        tmp_repo = owner + "/" + repo
                        data = "{},{},{},{},\"{}\",{}".format(tmp_repo, pr_url,
                                pr["state"], pr["type"], pr["title"], user)
                        print(data)
                        fp.write("{}\n".format(data))
                        fp.flush()
                    pr_page += 1
                    pr_list = src_counter.get_pr_list(repo, owner, state=state, page=pr_page)
            if all_repo_flag:
                page += 1
                repo_list_tmp = src_counter.get_repos(owner, page=page)
            else:
                break
    fp.close()

def get_list(arg):
    lst = []
    if os.path.isfile(arg):
        with open(arg, 'r') as f:
            for ln in f:
                lst.extend(ln.strip().split(" "))
    else:
        lst = list(arg.strip().split(" "))
    return lst

def main():
    """
    Main entrance of the functionality
    """
    params = argparse.ArgumentParser()
    params.add_argument("-u", "--user", type=str,
                        help="The username file or list")
    params.add_argument("-r", "--repo", type=str, default="",
                        help="The repository file or list, default is all repos")
    params.add_argument("-p", "--project", type=str, default="src-openeuler",
                        help="The project name, default is src-openeuler")
    params.add_argument("-s", "--state", type=str, default="open",
                        help="The state of PR, as follows: open, merged, closed, all")
    params.add_argument("-o", "--outfile", type=str, default="",
                        help="The output file, default is pr_{stat}_result.csv")

    args = params.parse_args()

    if not args.user:
        print("args invalid, please use -h for help")
        quit()

    user_list = get_list(args.user)
    if not user_list:
        print("user list invalid")
        quit()

    repo_list = []  # empty means all
    if args.repo != "":
        repo_list = get_list(args.repo)
        if not repo_list:
            print("repo list invalid")
            quit()

    if not args.outfile:
        outfile = "pr_{}_result.csv".format(args.state)
    else:
        outfile = args.outfile

    check_pr(user_list, repo_list, args.project, args.state, outfile)


if __name__ == "__main__":
    main()
